<template>
  <div>
    <el-form label-width="80px">
      <el-form-item label="数据导入">
        <el-button @click="handleImport" :loading="loadingImport">导入</el-button>
      </el-form-item>
      <el-form-item label="数据导出">
        <el-button @click="handleExport" :loading="loadingExport">导出</el-button>
      </el-form-item>
      <el-form-item label="清除数据">
        <el-button @click="clearData('all')">所有</el-button>
        <el-button @click="clearData('projectList')">项目</el-button>
        <el-button @click="clearData('serverList')">服务器</el-button>
        <el-button @click="clearData('deployRecords')">部署日志</el-button>
      </el-form-item>
      <el-form-item label="暗黑模式">
        <el-switch v-model="isDark" inline-prompt active-value="1" inactive-value="0" active-text="开"
          inactive-text="关" />
      </el-form-item>
      <el-form-item label="项目地址">
        <el-link type="primary" href="https://gitee.com/lijinbode/web-auto-deploy" target="_blank">
          码云：https://gitee.com/lijinbode/web-auto-deploy
        </el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { open } from '@tauri-apps/plugin-dialog'
import { readTextFile, writeTextFile } from '@tauri-apps/plugin-fs'
import { join } from '@tauri-apps/api/path'
import { database, dbTabelNames } from '@/utils/IndexDBWarp/index'
import { parseObj } from '@/utils/common'
import { confirmDialog, tips } from '@/utils/tips'
import { useLoadingBtn } from '@/hooks/useLoadingBtn'
import { useDarkTheme } from '@/hooks/useDarkTheme'


const [handleImport, loadingImport] = useLoadingBtn(async () => {
  const filePath = await open({
    multiple: false,
    title: '选择导入文件',
    filters: [{ name: 'json', extensions: ['json'] }]
  })
  const res = await readTextFile(filePath)
  const data = parseObj(res, {})

  for (let tableName of dbTabelNames) {
    if (Array.isArray(data[tableName])) {
      const store = database.getObjectStore(tableName)
      await store.bulkAdd(data[tableName])
    }
  }
  tips('导入成功')
})

const [handleExport, loadingExport] = useLoadingBtn(async () => {
  const data = {}
  for (let tableName of dbTabelNames) {
    const store = database.getObjectStore(tableName)
    data[tableName] = await store.getAll()
  }
  const dirPath = await open({
    multiple: false,
    title: '选择存放目录',
    directory: true
  })
  const filePath = await join(dirPath, 'data.json')
  await writeTextFile(filePath, JSON.stringify(data))
  tips('导出成功')
})

const { isDark } = useDarkTheme()

const clearData = async (tableName) => {
  if (tableName === 'all') {
    await confirmDialog(`确定清除所有表的数据吗？`)
    for (let tableName of dbTabelNames) {
      const store = database.getObjectStore(tableName)
      await store.clear()
    }
  } else {
    await confirmDialog(`确定清除 ${tableName} 表的数据吗？`)
    const store = database.getObjectStore(tableName)
    await store.clear()
  }
  location.reload()
  tips('清除成功')
}
</script>

<style scoped lang="scss"></style>
